package com.clp.protocol.iec104.apdu.asdu;

import com.clp.protocol.core.common.frame.InitializableFrameClip;
import com.clp.protocol.iec104.definition.Sq;
import io.netty.buffer.ByteBuf;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;

import java.util.Objects;

/**
 * 可变结构限定词
 */
@Getter
@NoArgsConstructor
@AllArgsConstructor
public class Vsq implements InitializableFrameClip<Vsq> {
    /**
     * 1个字节。第1位：sq=0为连续；sq=1为不连续。
     */
    private Sq sq;
    /**
     * 1个字节。后7位：信息元素的数目
     */
    private int num;

    @Override
    public Vsq initBy(ByteBuf buf) {
        byte by = buf.readByte();
        this.sq = Sq.gain((by & 0x80) == 0x80 ? 1 : 0);
        this.num = by & (byte) 0x7F;
        return this;
    }

    @Override
    public boolean isValid() {
        return sq != null && num >= 0 && num <= 0x7F;
    }

    @Override
    public void writeTo(ByteBuf buf) {
        byte by = 0x00;
        if (sq.getVal() == 1) by |= 0x80;
        by |= (byte) (num & 0x7F);
        buf.writeByte(by);
    }

    @Override
    public String toString() {
        return "<类型：" + sq.getDesc() + "(" + sq.getVal() + "), 个数：" + num + ">";
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Vsq vsq = (Vsq) o;
        return num == vsq.num && sq == vsq.sq;
    }

    @Override
    public int hashCode() {
        return Objects.hash(sq, num);
    }
}
